/**
 *
 * User: Zhikang.Peng
 * Date: 2018/06/25 09:35
 */
package heap

import (
	"unicode/utf16"
)

// 用map来表示字符串池，key是Go字符串，value是Java字符串
var internedStrings = map[string]*Object{}

func JString(loader *ClassLoader, goStr string) *Object {
	if internedStr, ok := internedStrings[goStr]; ok {
		return internedStr
	}
	chars := stringToUTF16(goStr)
	// 初始化char[]
	jChars := &Object{loader.LoaderClass("[C"), chars, nil}
	jString := loader.LoaderClass("java/lang/String").NewObject()
	jString.SetRefVal("value", "[C", jChars)
	internedStrings[goStr] = jString
	return jString
}

func stringToUTF16(s string) []uint16 {
	runes := []rune(s) // utf32
	return utf16.Encode(runes)
}

func utf16ToString(s []uint16) string {
	for i, v := range s {
		if v == 0 {
			s = s[0:i]
			break
		}
	}
	return string(utf16.Decode(s))
}

func GoString(jStr *Object) string {
	charArr := jStr.GetRefVal("value", "[C")
	return utf16ToString(charArr.Chars())
}

// todo
func InternString(jStr *Object) *Object {
	goStr := GoString(jStr)
	if internedStr, ok := internedStrings[goStr]; ok {
		return internedStr
	}

	internedStrings[goStr] = jStr
	return jStr
}
